﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Networking;
public class LoadAssetBundle : MonoBehaviour
{
    Dictionary <string,GameObject> dicGameObject;
    public static readonly string PathAndName;

    public static Action<EventTriggerType> ActIsRawImage;

#if UNITY_2018_1_OR_NEWER
    private UnityWebRequest uwr;
#else

    UnityWebRequest uwr;
#endif

    string AssetName;//预设节点名字
    private void Awake()
    {
        dicGameObject = new Dictionary<string, GameObject>();
    }

    void Start()
    {
        //StartCoroutine(LoadABwebRequest());//网络加载
    }

    public void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {

        }
    }

    public void OnGUI()
    {
        GUI.TextArea(new Rect(0 , 0, 80, 80),"AB包正在加载" +(uwr.downloadProgress*100).ToString());
    }
    //如果缓存里有 就从缓存里加载 ，如果没有就从文件里加载
    public void LoadABFromCaChe(string AssetName, string PathAndName,Vector3 Posion,Vector3 Rotation)
    {
        if (dicGameObject.ContainsKey(AssetName))//判断缓存里是否有这个
        {
            Instantiate(dicGameObject[AssetName]);//如果有就直接生成
        }
        else
        {
            //如果没有就加载并放入缓存
            StartCoroutine(LoadABwebRequest(AssetName, PathAndName,Vector3.zero,Vector3.zero));//网络加载
        }
    }           
    //本地和web加载
    IEnumerator LoadABwebRequest(string AssetName,string PathAndName, Vector3 Posion, Vector3 Rotation)
    {
#if UNITY_2018_1_OR_NEWER
         uwr = UnityWebRequestAssetBundle.GetAssetBundle(PathAndName);
#else
        uwr = UnityWebRequest.GetAssetBundle(PathAndName);
#endif
        yield return uwr.SendWebRequest();
        if (uwr.isNetworkError || uwr.isHttpError)
        {
            Debug.LogError(uwr.error);
        }
        else
        {
            AssetBundle ab = DownloadHandlerAssetBundle.GetContent(uwr);
            GameObject obj = ab.LoadAsset<GameObject>(AssetName);
            GameObject go = Instantiate(obj, Posion,Quaternion.Euler(Rotation));
            //go.AddComponent<BAT_MildBaker>();
            dicGameObject.Add(AssetName, obj);
            ab.Unload(false);
        }
    }
}

